// ==UserScript==
// @name         12306 test
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @include     http://*.12306.cn/*
// @include     https://*.12306.cn/*
// @include     https://mail.qq.com/*
// @run-at      document-end
// @grant        none
// ==/UserScript==

var Info = {ways:"潍坊-深圳;青岛-深圳",
    station:{深圳:'SZQ', 潍坊:"WFK" ,济南: "JNK",上海:"SHH",青岛:"QDK"} ,
    date:"2017-02-02",
    user12306:{user:"18098973875",passwd:""},
    passenger:"闫海霞",
    urlNotifyTicketAvaliable:"http://127.0.0.1:8080/tickitAvaliable",
    urlOrderSubmit:"http://127.0.0.1:8080",
    selectSeat:"yes"
};

function CheckOrder()
{
    var book = getCookie("_make_an_order");
    if (book == "yes")
        redirectURL("https://kyfw.12306.cn/otn/index/initMy12306");
}

function clickDingPiao()
{
    if ($("a.k2").html().indexOf("test") >= 0)
        return;
    cliclLink($("a.k2"));
    $(document).URL = "http://baidu.com";
}
if (document.URL == "http://www.12306.cn/mormhweb/" )//首页
{
    //window.open("http://baidu.com");
    //var span =  '<span id="mo2g">test</span>';
    //$("a.k2").html(span);
    //$("#mo2g").click();
    setTimeout(clickDingPiao,3000);
}
if (document.URL == "https://kyfw.12306.cn/otn/" )//车票查询
{
    //setCookie("ways","深圳-潍坊;深圳-济南-潍坊",null);
    //setCookie("深圳", "SZQ",null);
    //setCookie("潍坊", "WFK",null);
    //setCookie("济南", "JNK",null);
    //setCookie("上海", "SHH",null);
    //setCookie("青岛", "QDK",null);
    //setCookie("date", "2017-02-03;2017-02-02",null);

    setCookie("ways",Info.ways,null);
    for (k in Info.station)
    {
        setCookie(k, Info.station[k], null);
    }
    setCookie("date", Info.date, null);
    setCookie("selectSeat", Info.selectSeat,null);
    setDate();
    setFromToStation();
    $("#a_search_ticket").click();
}

function cliclLink(ele)
{
    if (ele.length === 0)
        return false;
    var id = ele.attr("id") || "2";
    id = "mo2g"+id;
    var span =  '<span id="'+id+'">test</span>';
    console.log("cliclLink:"+ ele.html());
    ele.html(span);
    $("#"+id).click();
    return true;
}
function  redirectURL(url)
{
    window.location.href = url;
}
function setDate()
{
    var tm =  $("#train_date").val();
    var wantDate = getCookie("date").split(";");
    var nextDate = "";
    for (var i = 0; i < wantDate.length; ++i)
    {
        if (tm == wantDate[i])
        {
            if (i+1 == wantDate.length)
                nextDate = wantDate[0];
            else
                nextDate=wantDate[i+1];
        }
    }
    if (nextDate === "")
        nextDate = wantDate[0];
    wantDate = nextDate.split("-");
    var dt = new Date();
    dt.setTime(dt.getTime() + 29*24*60*60*1000);
    var dt2 = new Date();
    dt2.setFullYear(parseInt(wantDate[0]),parseInt(wantDate[1]) - 1,parseInt(wantDate[2]));
    dt2.setHours(0);
    dt2.setMinutes(0);
    if (dt.getTime() > dt2.getTime())
    {
        dt.setTime(dt2.getTime() ) ;
    }
    var m = dt.getMonth() + 1;
    var m2 = m.toString();
    if (m < 10)
        m2 = "0"+ m2;
    var d = dt.getDate();
    if (d < 10)
        d ="0"+d;
    tm = dt.getFullYear() + "-" + m2 + "-" + d;
    $("#train_date").val(tm);
}
function setFromToStation()
{
    var from = "";
    var to = "";
    var curr_path = getCookie("currPath");
    var ways = getCookie("ways").split(";");
    var stations = 0;
    var x = 0;
    var y = 0;
    if (curr_path !== "")
    {
        curr_path = curr_path.split(",");
        x = parseInt(curr_path[0]);
        y = parseInt(curr_path[1]);
    }
   for (var i = 0; i < ways.length; ++i)
   {
       stations = ways[x].split("-");
       if (isWayBooked(stations[y] + "-" + stations[y+1]) )//当前定成功
       {
           while (y + 2 < stations.length)//有后续路径
           {
                from = stations[y+1];
                to = stations[y+2];
               y = y+1;
               if (isWayBooked(from+"-"+to))
               {
                   from = to = "";//不要再查了
                   continue;//下级也是成功的
               }
               else
                   break;
           }
           if (from !== "")
               break;
       }
        x += 1;
        y = 0;
        if (x == ways.length)
            x = 0;
        stations = ways[x].split("-");
        if (isWayBooked(stations[y] + "-" + stations[y+1]) )
        {
           continue;
        }
        from = stations[y];
        to = stations[y+1];
       break;
   }
    if (from === "")
    {
        redirectURL("https://kyfw.12306.cn/otn/index/initMy12306");//找不可查的路径,就查订单的状
        return;
    }
    k1 = getCookie(from);
    k2 = getCookie(to);
    $("#toStationText").val(to);
    $("#toStation").val(k2);

    $("#fromStationText").val(from);
    $("#fromStation").val(k1);
    setCookie("currPath", x+","+y, null);
}
function isWayBooked(way)//way = "深圳-济南"
{
    state=arguments[1]?arguments[1]:null;
    if (state === null)
    {
        state = getCookie("order_" + way);
        if (state == "yes")
            return true;
        return false;
    }
    setCookie("order_" + way, state,null);
}

function clickSearch(timeout)
{
    var lastpath = getCookie("currPath");
    setFromToStation();
    var currpath = getCookie("currPath");
    if (lastpath !== currpath && currpath == "0,0")
        setDate();
    cliclLink($("#query_ticket"));
    cliclLink($("#query_ticket"));
    //setTimeout(CheckTick,timeout);
}

var SoundPlayed = 0;
var EmptyTableTimes = 0;
function CheckTick()
{
    if ($("div.dhtmlx_window_active").find("#username").length > 0)
    {
        //显示了登陆界面
        if (SoundPlayed === 0){
            $("#username").val(Info.user12306.user);
            $("#password").val(Info.user12306.passwd);
            window.open(Info.urlNotifyTicketAvaliable);
            console.log(Info.urlNotifyTicketAvaliable + " " + SoundPlayed);
        }
        SoundPlayed += 1;
        if (SoundPlayed > 120)
        {
            redirectURL("https://kyfw.12306.cn/otn/leftTicket/init");
        }
        return;
    }
    if ($("#queryLeftTable").children().length === 0)
    {
        ++EmptyTableTimes;
        console.log("len=" + $("#queryLeftTable").children().length);
        if (EmptyTableTimes < 3){
        //setTimeout(CheckTick,500);
        return;
        }
        EmptyTableTimes = 0;
    }
    if ($("td.no-br").length === 0)
    {
        clickSearch(2000);//没有预定按钮，点搜索
    }
    else
    {
        var booked = false;
       for (i = 0; i < $("td.no-br").length; i++){
           booked = BookTickt($("td.no-br")[i]);
           if (booked)
               break;
       }
       if ( ! booked)
       {
           clickSearch(2000);
       }
    }

}
function isSeatAvaliable(ele)
{
    if (getCookie("selectSeat") != "yes") {
        window.open(Info.urlNotifyTicketAvaliable);
        return true;
    }
    needGT=arguments[1]?arguments[1]:null;
    var rw =  $(ele).parent().children(":eq(6)").html().trim();
    var yw =  $(ele).parent().children(":eq(7)").html().trim();
    var erdz =  $(ele).parent().children(":eq(4)").html().trim();
    rw = (rw.indexOf("无") > -1 || rw.indexOf("-") > -1);
    yw = (yw.indexOf("无") > -1 || yw.indexOf("-") > -1);
    erdz = (erdz.indexOf("无") > -1 || erdz.indexOf("-") > -1);
    if (needGT == "yes")
    {
        if (erdz)
            return false;
        window.open(Info.urlNotifyTicketAvaliable);
        return true;
    }
    if ( rw && yw && erdz)
        return false;
    window.open(Info.urlNotifyTicketAvaliable);
    return true;
}
function BookTickt(ele)
{
    if ($(ele).children().length === 0)
    {
        return false;
    }
    var a = $(ele).parent().find("a.number").html();
    setCookie(a, $("#fromStationText").val()+"-"+($("#toStationText").val()));
    var time = "";
    var rw =  $(ele).parent().children(":eq(6)").html().trim();
    var yw =  $(ele).parent().children(":eq(7)").html().trim();
    var erdz =  $(ele).parent().children(":eq(4)").html().trim();
    if ($("#toStation").val() == "JNK") //只要高铁
    {
        time = $(ele).parent().find("div.ls").children("strong").html().trim();
        if (time[0] != "1")//认为高铁在20小时以下
            return false;
        if (!isSeatAvaliable(ele,"yes"))
            return false;
        time =  $(ele).parent().find("div.cds").children("strong.color999").html().trim();
        setCookie("time_to_JNK",time);
        $(ele).children("a").click();
    }
    else if ($("#toStation").val() == "WFK")
    {
        if ($("#fromStation").val() == "SZQ" ) //从深圳-潍坊
        {
            if (!isSeatAvaliable(ele))
                return false;
            $(ele).children("a").click();//随便订
        }
        else if ($("#fromStation").val() == "JNK")//济南-潍坊
        {
            //到济南的后的2小时的票
            time = getCookie("time_to_JNK");
            if (time === "")
                return false;
            time = time.split(":");
            var dt = new Date();
            dt.setHours(time[0]);
            dt.setMinutes(time[1]);
            dt.setTime(dt.getTime() + 2*60*60*1000);//两小时后
            time = dt;
            dt = new Date();
            var t = $(ele).parent().find("div.cds").children("strong.start-t").html().trim();
            t = t.split(":");
            dt.setHours(t[0]);
            dt.setMinutes(t[1]);
            console.log(a+" JN(" + getCookie("time_to_JNK") + ") to WF " + time);
            if (dt.getTime() < time.getTime())
                return false;
            $(ele).children("a").click();
        }
        else if ( $("#fromStation").val() == "SHH") //上海
        {
            console.log(a+" to WF " + rw + " " + yw + " " + erdz);
            if ( !isSeatAvaliable(ele) )
                return false;
            $(ele).children("a").click();//随便订
        }
    }
    else
    {
        if (!isSeatAvaliable(ele))
            return false;
        $(ele).children("a").click();//随便订
    }
    return true;
}

if (document.URL == "https://kyfw.12306.cn/otn/leftTicket/init") //剩余车票显示页
{
    setInterval(CheckTick,5000);
}
function setCookie(c_name,value,expiredays)
{
    //var exdate=new Date();
    //exdate.setDate(exdate.getDate()+expiredays);
    console.log("set:"+c_name+ "=" + value);
    //document.cookie = c_name+ "=" +escape(value)+ ((expiredays===null) ? "" : ";expires="+exdate.toGMTString());
    window.localStorage.setItem(c_name,value);
}
function getCookie(c_name)
{
    var val = "";
    //if (document.cookie.length>0)
    //{
    //    c_start=document.cookie.indexOf(c_name + "=");
    //    if (c_start!=-1)
    //    {
    //        c_start=c_start + c_name.length+1 ;
    //        c_end=document.cookie.indexOf(";",c_start);
    //        if (c_end==-1) c_end=document.cookie.length;
    //            val = unescape(document.cookie.substring(c_start,c_end));
    //    }
    //}
    val = window.localStorage.getItem(c_name);
    if (val === null)
        val = "";
    console.log("get:"+c_name+ "=" + val);
    return val;
}
function ClickPassenger(name)
{
    var peoples = $("#normal_passenger_id").find("label[style='cursor: pointer']");
    if (peoples.length === 0) {
        setTimeout(SubmitOrder,500);
        return false;
    }
    var i = 0;
    var allCheck = false;
    for (i = 0; i < peoples.length; i++){
        if ($(peoples[i]).html() != name )
            continue;
        if ($(peoples[i]).attr("class") !== "colorA")
            $(peoples[i]).prev().click();
        allCheck = true;
    }
    return allCheck;
}
function clickSeat()
{
    $("#ticketInfo_id").find("select").each(function(){
        if ($(this).attr("id").indexOf("seatType_") === -1)
            return;
        var seats = {edz:-1, rw:-1,yw:-1};
        $(this).find("option").each(function(index,element){
            console.log("option:"+$(this).html());
            if ($(this).html().trim() == "二等座")
                seats.edz = $(this);
            if ($(this).html().trim() == "硬卧")
                seats.yw = $(this);
            if ($(this).html().trim() == "软卧")
                seats.rw = $(this);
        });
        if (seats.edz == -1 && seats.rw == -1 && seats.yw == -1)
            return;
        $(this).find("option").removeAttr("selected");
        if (seats.edz)
            seats.edz.attr("selected","selected");
        else if (seats.rw)
            seats.rw.attr("selected","selected");
        else if (seats.yw)
            seats.yw.attr("selected","selected");
    });
    return true;
}
function setCurrWayBooked()
{
   // var strong = $("#ticket_tit_id").children("strong");
    var strong = $("#show_title_ticket").children("strong");
    var s = strong[1].innerHTML;
    console.log("train="+s);
    s = s.split(" ")[0];
    s = getCookie(s);
    isWayBooked(s, "yes");
}
function clickSubmitBtn()
{
    if (!cliclLink($("#qr_submit_id.btn92s")))
    {
        console.log("click qr_submit_id error!");
    }
}
var submitStep = 0;
function SubmitOrder()
{
    submitStep += 1;
    if (submitStep === 1)
    {
        var pssg = Info.passenger.split(",");
        for (var i = 0; i < pssg.length; ++i)
        {
            if (!ClickPassenger(pssg[i]))
                return;
        }
        if (!clickSeat())
        {
           return;
        }
    }
    else if (submitStep === 2)
    {
        if (!cliclLink($("#submitOrder_id")))
        {
            return;
        }
    }
    else if (submitStep === 3)
    {
        //setCurrWayBooked();
        setTimeout(clickSubmitBtn,2000);
    }
    else if (submitStep > 20)
    {
        redirectURL( "https://kyfw.12306.cn/otn/leftTicket/init");
    }
}
if (document.URL == "https://kyfw.12306.cn/otn/confirmPassenger/initDc")
{
     setInterval( SubmitOrder, 1000);
}
if (document.URL.indexOf("https://kyfw.12306.cn/otn//payOrder/init?random=") > -1)//提交定单后跳转页
{
    window.open(Info.urlOrderSubmit);
    setCurrWayBooked();
}
function checkOrderCancel()
{
    var ways = getCookie("ways");
    ways = ways.split(";");
    var lst = [];
    for (var i = 0; i < ways.length; ++i)
    {
        var s = ways[i].split("-");
        for (var j = 0; j < s.length -1; ++j)
        {
            lst.push([s[i], s[i+1]]);
        }
    }
    var hasOrder = false;
    $("div.order-item").each(function(){
        ways = $(this).find("div.ccxx").html();
        for(var i = 0; i < lst.length; ++i)
        {
            if (ways.indexOf(lst[i][0]) > -1 && ways.indexOf(lst[i][1]) > -1 )
            {
                lst[i].push("tickt_ok");
                hasOrder = true;
            }
        }
    });
    for(i = 0; i < lst.length; ++i)
    {
        if (lst[i].length == 2)
        {
            isWayBooked(lst[i][0]+"-"+lst[i][1],"no");
        }
    }
    if (!hasOrder)
    {
        redirectURL( "https://kyfw.12306.cn/otn/leftTicket/init");
        return;
    }
    redirectURL( "https://kyfw.12306.cn/otn/queryOrder/initNoComplete");
}
if (document.URL == "https://kyfw.12306.cn/otn/queryOrder/initNoComplete")
{
    //检查未处理订单，如果未清理定单清零，重新开始订
    setInterval(checkOrderCancel, 5000);
}
if (document.URL == "https://kyfw.12306.cn/otn/login/init")
{
    //检查未处理订单，如果未清理定单清零，重新开始订
    $("#username").val(Info.user12306.user);
    $("#password").val(Info.user12306.passwd);
}